<template>
  <div class="room">
    <logo-vue class="logo"></logo-vue>
    <enter-animation v-if="hintMessage" :message="hintMessage"></enter-animation>
    <music-vue v-else></music-vue>
    <div class="room_box">
      <div class="user_list">
        <user-list v-if="RoomInfo" :RoomInfo="RoomInfo" :UserList="UserList" @removeRoom="removeRoom"></user-list>
      </div>
      <div class="chat_box">
        <chat-view :message="message"></chat-view>
        <send-view @send="sendMessage"></send-view>
      </div>
    </div>
  </div>
</template>

<script>
import logoVue from "../../header/logo.vue"
import enterAnimation from "./enterAnimation.vue"
import userList from "./userList.vue"
import chatView from "./chatView.vue"
import sendView from "./sendView.vue"
import musicVue from "./music.vue"
import { mapActions } from 'vuex'
export default {
  name: 'Room',

  data() {
    return {
      RoomInfo: null, // 当前房间信息
      socket: null, // Websocket连接
      message: null, // 所有消息数据集
      UserList: null, // 当前房间所有用户数据集
      hintMessage: null, // 进入房间动画信息
      beforeUnload_time: null, // 关闭页面的时间
      gap_time: null // 确认关闭页面的时间
    };
  },

  mounted() {
    this.init()
    window.addEventListener('beforeunload',e => this.beforeunload(e))
    window.addEventListener('unload', e => this.unload(e))
  },

  destroyed(){
    window.removeEventListener('beforeunload',e => this.beforeunload(e))
    window.removeEventListener('unload', e => this.unload(e))
  },

  methods: {
    // 进入房间，初始化
    init(){
      this.hintMessage = '正在进入房间...'
      setTimeout(this.toLogin,1000)
    },
    // 登陆验证
    toLogin(){
      this.hintMessage = '正在登陆验证...'
      this.$api.toLogin().then(res => {
        if(res instanceof Object){
          this.$store.commit('getUserInfo',res)
          setTimeout(this.getRoomInfo,1000)
        }else{
          this.showHint({title:'请先登陆',isFlag:false})
          this.$router.push('/chat')
        }
      })
    },
    // 获取房间信息
    getRoomInfo(){
      const id = this.$route.query.id
      console.log(id)
      const password = this.$route.query.password
      this.hintMessage = '获取房间信息...'
      this.$api.getRoomInfo({id}).then(res => {
        if(res instanceof Object){
          document.title = res.title
          this.RoomInfo = res
          if(res.password && res.password != password){
            this.showHint({title:'房间已加密!',isFlag:false})
            setTimeout(() => {this.$router.push('/chat')},1000)
            return
          }
          setTimeout(this.toRoom,1000)
        }else{
          this.showHint({title:res,isFlag:false})
          setTimeout(() => {this.$router.push('/chat')},1000)
        }
      })
    },
    // 进入房间
    toRoom(){
      const id = this.RoomInfo.chatid
      this.hintMessage = '正在连接房间...'
      this.socket = this.$websocket.getChatRoom(id)
      this.socket.onmessage = (e) => {
        let data = JSON.parse(e.data)
        switch(data.key){
          case 101: this.message = this.$store.state.userinfo.username == data.username ? '' : data ;break; // 获取到新消息
          case 102: this.UserList = data;break; // 发现用户变更
          case 103: this.offRoom();break; // 房间解散
          case 500: this.anewtoRoom();break; // 重新连接
          default: this.showHint({title:data,isFlag:false});break;
        }
      }
      this.socket.onerror = () => {
        this.showHint({title:'连接失败',isFlag:false})
        setTimeout(()=>{window.close()},1000)
      }
      setTimeout(() =>{
        if(this.socket.readyState == 1){
          this.send({key:102})
          this.hintMessage = null
        }
      },2000)
    },
    // 发送心跳
    send(message){
      if(this.socket && this.socket.readyState == 1){
        this.socket.send(JSON.stringify({message}))
      }else{
        this.showHint({title:'连接断开,正在尝试重新建立连接!',isFlag:false})
        this.toRoom()
      }
    },
    // 退出房间
    exitRoom(){
      this.socket.close()
      this.socket = null
    },
    // 房间解散
    offRoom(){
      alert('房主已解散该房间!')
      window.close()
    },
    // 房主解散房间
    removeRoom(){
      this.send({key:103})
    },
    // 发送聊天信息
    sendMessage(content){
      this.send({username: this.$store.state.userinfo.username,content,key: 101})
    },
    // 重新连接
    anewtoRoom(){
      if(confirm('连接断开,是否重连?')){
        this.toRoom()
      }else{
        window.close()
      }
    },
    // 关闭页面离开房间
    beforeunload(){
      this.beforeUnload_time=new Date().getTime()
    },
    unload(){
      this.gap_time=new Date().getTime()-this.beforeUnload_time;
      console.log(this.gap_time)
      if(this.gap_time <= 5){
        this.exitRoom()
      }
    },
    ...mapActions(['showHint'])
  },

  components: {
    enterAnimation,userList,chatView,sendView,logoVue,musicVue
  }
};
</script>

<style scoped>
.room{
  width: 100vw;
  height: 100vh;
  background-color: #ececec;
  background-image: url('../../../assets/image/gif/adminBG.gif');
  background-size: cover;
}
.room_box{
  width: 80%;
  background-color: white;
  border-radius: 10px;
  border: 1px solid gray;
  box-shadow: 0 0 4px gray;
  animation: room 3s ease infinite;
  display: flex;
  background-color: #ececec;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
.room_box .user_list{
  flex: 1;
}
.room_box .chat_box{
  flex: 5;
  font-size: 0.8rem;
}
.room .logo{
  position: fixed;
  left: 10px;
  top: 10px;
}

@keyframes room {
  0%{
    box-shadow: 0 0 4px gray;
  }
  50%{
    box-shadow: 0 0 10px rgb(161, 250, 149);
  }
  100%{
    box-shadow: 0 0 4px gray;
  }
}

@media screen and (max-width: 468px) {
  .room_box{
    width: 100%;
    height: 100vh;
    position: relative;
    top: 0;
    left: 0;
    flex-direction: column;
    transform: none;
  }
  .room_box .chat_box{
    width: 100%;
    padding: 0;
    display: flex;
    flex-direction: column;
  }
}
</style>